import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_widgets/widgets/formItem/kq_numer_item_view.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 动态添加 原因选择+数量
///
/// [ItemType.addNumber]
///
/// 左边删除图标 + 标题 + 选择原因 + 下拉图标 + 数量减按钮  + 数量输入框 + 数量加按钮 + 单位
///
/// 结合 KqFormEntity 使用
///
/// 标题：title
/// 选择提示：hint
/// 选择的显示值使用：valueForShow
/// 选择的提交值使用:valueForSubmit
/// 数字值使用：qty
///
/// @author 周卓
///
class KqAddNumberItemView extends StatefulWidget {
  /// 数据
  final KqFormEntity entity;

  /// 选择控件点击回调
  final Function(KqFormQtyEntity entity)? onQtyTap;

  const KqAddNumberItemView({Key? key, required this.entity, this.onQtyTap})
      : super(key: key);

  @override
  KqAddNumberItemViewState createState() => KqAddNumberItemViewState();
}

class KqAddNumberItemViewState extends State<KqAddNumberItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    if (widget.entity.extraData == null) {
      widget.entity.extraData = <KqFormQtyEntity>[];
      _addRow();
    } else {
      checkListener();
    }
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 检查点击事件是否漏掉
  checkListener() {
    widget.entity.extraData ??= <KqFormQtyEntity>[];
    for (KqFormQtyEntity entity in widget.entity.extraData) {
      entity.onTap ??=
          (entity) => widget.entity.onQtyTap?.call(widget.entity, entity);
      entity.onRemove ??= (entity) => {_removeRow(entity)};
      entity.onNumberQtyChanged ??= (entity) {
        widget.entity.onNumberQtyChanged?.call(widget.entity, entity);
      };
    }
    //必填时，限制最少1条
    if (widget.entity.mustInput && widget.entity.extraData.length == 1) {
      widget.entity.extraData[0].removable = false;
    } else {
      for (var value in widget.entity.extraData) {
        value.removable = true;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    checkListener();
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ??
        KqThemeManager.getFormConfig().backgroundColor ??
        KqThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          Container(
            color: bgColor,
            padding: EdgeInsets.only(
                right: widget.entity.paddingHorizontal ??
                    KqThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    16.r),
            child: Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                      right: widget.entity.titleRightMargin ??
                          (widget.entity.title.isNotEmpty ? 8.r : 0)),
                  child: Row(
                    children: <Widget>[
                      ///是否必填
                      Container(
                        alignment: Alignment.centerRight,
                        width: widget.entity.paddingHorizontal ??
                            KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .paddingHorizontal ??
                            16.r,
                        padding: EdgeInsets.only(right: 2.r),
                        child: Text(
                          "∗",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontSize: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .mustInputFontSize ??
                                  14.sp,
                              color: (widget.entity.mustInput &&
                                          widget.entity.isEditable()) ||
                                      (!widget.entity.isEditable() &&
                                          widget.entity.forceShowMushInput)
                                  ? KqThemeColors.textRed
                                  : KqThemeColors.bgTransparent),
                        ),
                      ),

                      ///标题
                      Padding(
                        padding: EdgeInsets.symmetric(
                            vertical: widget.entity.paddingVertical ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingVertical ??
                                15.r),
                        child: LimitedBox(
                          maxWidth: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .titleMaxWidth ??
                              200.r,
                          child: Text(
                            widget.entity.title,
                            maxLines: widget.entity.multiline ? null : 1,
                            overflow: widget.entity.multiline
                                ? null
                                : TextOverflow.ellipsis,
                            style: widget.entity.titleStyle ??
                                TextStyle(
                                    fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .titleFontSize ??
                                        16.sp,
                                    color: widget.entity.titleColor ??
                                        KqThemeManager.getFormConfig()
                                            .titleTextColor ??
                                        KqThemeColors.text26),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Expanded(
                    child: Row(
                  children: [
                    Expanded(
                        child: Text(
                      '${KqIntl.currentResource.total} ${widget.entity.extraData.length} ${KqIntl.currentResource.bar}',
                      textAlign: TextAlign.start,
                      style: TextStyle(
                          fontSize: 14.sp,
                          color: widget.entity.contentColor ??
                              KqThemeManager.getFormConfig()
                                  .contentTextColor ??
                              KqThemeColors.text8C),
                    )),
                    Visibility(
                      visible: widget.entity.isEditable() &&
                          (widget.entity.numberItemMaxRows == null ||
                              (widget.entity.numberItemMaxRows != null &&
                                  (widget.entity.extraData?.length ?? 0) <
                                      widget.entity.numberItemMaxRows!)),
                      child: InkWell(
                        onTap: () {
                          _addRow();
                          widget.entity.onAddNumberItem?.call(
                              widget.entity, widget.entity.extraData.last);
                        },
                        child: Container(
                            alignment: Alignment.centerRight,
                            height: 44.r,
                            child: Image.asset(
                              Images.commonIcAddFill,
                              width: 18.r,
                              height: 18.r,
                              fit: BoxFit.fill,
                              color: KqThemeManager.getCommonConfig()
                                  .mainLightColor,
                              package: KqGlobal.packageName,
                            )),
                      ),
                    )
                  ],
                ))
              ],
            ),
          ),
          KqDivider(
            leftMargin: !widget.entity.dividerHorMarginEnable ? 0 : widget.entity.paddingHorizontal ??
                KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .paddingHorizontal ??
                16.r,
            rightMargin: !widget.entity.dividerHorMarginEnable ? 0 : widget.entity.paddingHorizontal ??
                KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .paddingHorizontal ??
                16.r,
          ),
          Container(
              color: KqThemeColors.bgF4,
              child: ListView(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: _buildCell(),
              ))
        ],
      ),
    );
  }

  //添加行
  void _addRow() {
    widget.entity.extraData ??= <KqFormQtyEntity>[];
    setState(() {
      widget.entity.extraData.add(KqFormQtyEntity(
        hint: widget.entity.hint,
        unit: widget.entity.unit,
        fixedUnitWidth: widget.entity.fixedUnitWidth,
        minQty: widget.entity.minQty,
        qty: widget.entity.qty,
        onNumberQtyChanged: (entity) {
          widget.entity.onNumberQtyChanged?.call(widget.entity, entity);
        },
        onRemove: (entity) => {_removeRow(entity)},
        onTap: (entity) => widget.entity.onQtyTap?.call(widget.entity, entity),
      ));
      //必填时，限制最少1条
      if (widget.entity.mustInput && widget.entity.extraData.length == 1) {
        widget.entity.extraData[0].removable = false;
      } else {
        for (var value in widget.entity.extraData) {
          value.removable = true;
        }
      }
      widget.entity.onQtyListChanged
          ?.call(widget.entity, widget.entity.extraData);
    });
  }

  // 删除行
  void _removeRow(KqFormQtyEntity entity) async {
    if (widget.entity.onRemoveNumberItem != null) {
      bool deleteOk =
          await widget.entity.onRemoveNumberItem!(widget.entity, entity);
      if (deleteOk) {
        setState(() {
          widget.entity.extraData.remove(entity);
          //必填时，限制最少1条
          if (widget.entity.mustInput && widget.entity.extraData.length == 1) {
            widget.entity.extraData[0].removable = false;
          } else {
            for (var value in widget.entity.extraData) {
              value.removable = true;
            }
          }
          widget.entity.onQtyListChanged
              ?.call(widget.entity, widget.entity.extraData);
        });
      }
    } else {
      setState(() {
        widget.entity.extraData.remove(entity);
        //必填时，限制最少1条
        if (widget.entity.mustInput && widget.entity.extraData.length == 1) {
          widget.entity.extraData[0].removable = false;
        } else {
          for (var value in widget.entity.extraData) {
            value.removable = true;
          }
        }
        widget.entity.onQtyListChanged
            ?.call(widget.entity, widget.entity.extraData);
      });
    }
  }

  // 数量控件列表
  _buildCell() {
    if (widget.entity.extraData is List<KqFormQtyEntity>) {
      List<KqFormQtyEntity> data = widget.entity.extraData;
      return data.map((e) => KqNumberItemView(entity: e)).toList();
    }
    return [];
  }
}
